<template>
	<view class="u-wrap" :style="{'height':height+'px'}">
		<view class="u-menu-wrap">
			<scroll-view scroll-y scroll-with-animation class="u-tab-view menu-scroll-view" :scroll-top="scrollTop"
				:scroll-into-view="itemId">
				<view v-for="(item, index) in leftMenus" :key="index" class="u-tab-item"
					:class="[leftMenusCurrent == index ? 'u-tab-item-active' : '']" @tap.stop="swichMenu(index)">
					<text class="u-line-1">{{ item.name }}</text>
				</view>
			</scroll-view>
			<view class="right-box">
				<view class="font-24">
					<u-tabs :list="msupplierTabbar" :current="msupplierTabbarCurrent" @click="msupplierTabClick"
						:activeStyle="tabbarActiveStyle" lineColor="#675f91"></u-tabs>
					<u-line></u-line>
				</view>
				<view class="font-24">
					<u-tabs :list="tabbar" :current="tabbarCurrent" @click="tabClick" :activeStyle="tabbarActiveStyle"
						lineColor="#675f91"></u-tabs>
					<u-line></u-line>
				</view>
				<sort :value="sortType" @change="sort" type="material">
					<view class="flex" slot="right" style="justify-content: flex-end;">
						<picker @change="bindPicker" :value="pickerValue" :range="pickerArr">
							<view class="flex btn-picker">
								<view class="mr10">
									{{pickerArr[pickerValue]}}
								</view>
								<u-icon name="eye" color="#675f91"></u-icon>
							</view>
						</picker>
					</view>
				</sort>
				<scroll-view scroll-y scroll-with-animation class="flex-1 scroll-view" :scroll-into-view="scrollViewId"
					@scrolltolower="scrolltolower">
					<view class="page-view">
						<view class="item-container">
							<template v-for="v in list">
								<view :key="v.id" :id="'scrollView_'+v.id">
									<view class="blank20"></view>
									<view class="flex">
										<view class="flex-1" @click="materialEdit(v)">
											<text class="font-bold">{{v.mname}}</text>
										</view>
										<view class="font-24 mr15" v-show="set.purchase_unit_id">
											<text class="text-light-gray">单位：</text>{{v.purchase_unit_id[1]}}
										</view>
										<view class="" v-show="!valueObj[v.id] || valueObj[v.id] == 0">
											<u-button type="primary" size="mini" text="添加" :plain="true" @click="add(v.id)"></u-button>
										</view>
										<view class="" v-show="valueObj[v.id] && valueObj[v.id] > 0">
											<u-number-box v-model="valueObj[v.id]" @change="valChange" :min="min" :name="v.id"
												:asyncChange="true" bgColor="#ffffff" @overlimit="overlimit" :buttonSize="20"
												:step="v.purchase_increment||1">
												<view slot="minus" class="minus">
													<u-icon name="minus" size="12"></u-icon>
												</view>
												<view slot="plus" class="plus">
													<u-icon name="plus" size="12"></u-icon>
												</view>
											</u-number-box>
										</view>
									</view>
									<view class="blank10"></view>
									<view class="flex font-24" style="flex-wrap: wrap;">
										<view class="info-item" v-show="set.stock_qty_unit">
											<text class="text-light-gray">库存：</text>
											{{v.stock_qty_unit}}
										</view>
										<view class="info-item" v-show="set.main_price">
											<text class="text-light-gray">单价：</text>￥{{v.main_price}}/{{v.main_unit_id[1]}}
										</view>
										<view class="info-item" v-show="set.brand">
											<text class="text-light-gray">品牌：</text>{{v.brand == '无'?'-':v.brand}}
										</view>
										<view class="info-item" v-show="set.spec">
											<text class="text-light-gray">规格：</text>{{v.spec?v.spec:'-'}}
										</view>
										<view class="info-item" v-show="set.model">
											<text class="text-light-gray">型号：</text></text>{{v.model == '无'?'-':v.brand}}
										</view>
										<view class="info-item" v-show="set.default_msupplier_id">
											<text class="text-light-gray">默认供应商：</text>{{v.default_msupplier_id?v.default_msupplier_id[1]:''}}
										</view>

										<!-- <view v-show="set.default_msupplier_id">
											<view class="flex font-24" style="justify-content: space-between;    align-items: baseline;">
												<view class=" flex-1">
													<text class="text-light-gray">默认供应商：</text>{{v.default_msupplier_id?v.default_msupplier_id[1]:''}}
												</view>
											</view>
											<view class="blank20"></view>
										</view> -->
									</view>
									<view class="blank10"></view>
									<u-line></u-line>
								</view>

							</template>
							<view class="blank20"></view>
							<view class="flex" style="justify-content: center;" v-if="list.length<allList.length">
								<view class="">
									<u-loading-icon size="16"></u-loading-icon>
								</view>
								<view class="ml15 text-light-gray">
									加载中
								</view>
							</view>
							<view class="flex" style="justify-content: center;" v-if="list.length == allList.length">
								<view class="text-light-gray">
									没有了
								</view>
							</view>
							<view class="blank20"></view>
							<view class="blank20"></view>
						</view>
					</view>
				</scroll-view>
			</view>
		</view>
	</view>
</template>

<script>
	import sort from "@/components/sort.vue";
	export default {
		name: "material-list",
		components: {
			sort
		},
		props: {
			height: Number,
			scroll_id: Number, //食材id
			data: Array,
			menu: Array,
			isedit: Boolean,
			init_value: Array,
			loadtime: Number,
			set: Object,
			page: {
				type: String,
				default: 'food'
			},
		},
		data() {
			return {
				leftMenus: [],
				list: [],
				allList: [],
				leftMenusCurrent: 0,
				itemId: "", // 栏目右边scroll-view用于滚动的id
				scrollTop: 0, //tab标题的滚动条位置
				oldScrollTop: 0,
				material_tree: {},
				material_obj: {},
				msupplier_obj: {},
				tabbar: [],
				tabbarCurrent: 0,
				tabbarActiveStyle: {
					color: '#675f91'
				},
				msupplierTabbar: [],
				msupplierTabbarCurrent: 0,
				scrollViewId: '',
				valueObj: {},
				min: 0,
				pageSize: 15,
				sortType: '', //price_desc,price_asc,stock_desc,stock_asc
				pickerArr: ['食材+报价', '仅看报价单', '仅看食材库'],
				pickerValue: 0
			};
		},
		watch: {
			scroll_id(newVal, oldVal) {
				if (newVal == 0) return;
				let id = newVal;
				let v = this.material_obj[id];
				let top_category_id = v.top_category_id[0];
				let msupplier_id = v.default_msupplier_id[0];
				let sec_category_id = v.sec_category_id[0];
				let leftMenusCurrent = this.leftMenus.findIndex(m => m.id == top_category_id);
				this.leftMenusCurrent = leftMenusCurrent;
				this.updataMsupplierTabbar();
				let msupplierTabbarCurrent = this.msupplierTabbar.findIndex(m => m.id == msupplier_id);
				this.msupplierTabbarCurrent = msupplierTabbarCurrent;
				this.updataTabbar();
				let tabbarCurrent = this.tabbar.findIndex(m => m.id == sec_category_id);
				this.tabbarCurrent = tabbarCurrent;
				this.pickerValue = 0;
				this.updataList(id);
			},
			// init_value: {
			// 	handler(newVal, oldVal) {
			// 		this.updataValueObj(0, newVal);
			// 	},
			// 	immediate: false,
			// 	deep: true
			// },
			loadtime(newVal, oldVal) {
				if (newVal != oldVal) {
					this.init();
				}
			}
		},
		computed: {
			is_quote() {
				return this.pickerValue != 2;
			},
			is_material() {
				return this.pickerValue != 1;
			},
		},
		created() {
			this.init();
			this.updataValueObj(1);
		},
		methods: {
			bindPicker(e) {
				let index = e.detail.value;
				if (this.pickerValue != index) {
					this.pickerValue = index;
					this.updataList();
				}
			},
			sort(type) {
				this.sortType = type;
				this.updataList();
			},
			sortList(list) {
				let sortType = this.sortType;
				// price_desc,price_asc,stock_desc,stock_asc
				switch (sortType) {
					case 'price_desc':
						list.sort((a, b) => Number(b.main_price) - Number(a.main_price));
						break;
					case 'price_asc':
						list.sort((a, b) => Number(a.main_price) - Number(b.main_price));
						break;
					case 'stock_desc':
						list.sort((a, b) => this.formatPrice(b.stock_qty_unit) - this.formatPrice(a.stock_qty_unit));
						break;
					case 'stock_asc':
						list.sort((a, b) => this.formatPrice(a.stock_qty_unit) - this.formatPrice(b.stock_qty_unit));
						break;
					default:
						break;
				}
			},
			updataValueObj(isCreated, init_value) {
				this.valueObj = {};
				if (init_value) {
					init_value.forEach(v => {
						this.valueObj[v.id] = v.value;
					})
				} else {
					this.init_value.forEach(v => {
						this.valueObj[v.id] = v.value;
					})
				}
				if (!isCreated) {
					this.$forceUpdate();
				}
			},
			init() {
				// console.log(this.data);
				this.pickerValue = 0;
				this.leftMenusCurrent = 0;
				let material_tree = {};
				let leftMenus = [];
				let menuObj = {};
				let material_obj = {};
				let msupplier_obj = {};
				let material_top_category = this.$store.getters.get_material_top_category;
				let material_second_category = this.$store.getters.get_material_second_category;
				let msupplier = this.$store.getters.get_msupplier;
				let material_purchase_unit_category = this.$store.getters.get_material_purchase_unit_category;
				
				this.data.forEach(v => {
					let top_category_id;
					let sec_category_id;
					let msupplier_id;
					if(v.top_category_id[0]){
						top_category_id = v.top_category_id[0]
					}else{
						top_category_id = v.top_category_id;
					}
					if(v.sec_category_id[0]){
						sec_category_id = v.sec_category_id[0]
					}else{
						sec_category_id = v.sec_category_id;
					}
					if(v.default_msupplier_id[0]){
						msupplier_id = v.default_msupplier_id[0]
					}else{
						msupplier_id = v.default_msupplier_id;
					}
					let top_category_name = '';
					let sec_category_name = '';
					let msupplier_name = '';
					try{
						top_category_name = material_top_category.find(v=> v.id == top_category_id).name;
						sec_category_name = material_second_category.find(v=> v.id == sec_category_id).name;
						msupplier_name = msupplier.find(v=> v.id == msupplier_id).supplier_nick_name;
					}catch(e){
						//TODO handle the exception
					}
					v.top_category_id = [top_category_id,top_category_name];
					v.sec_category_id = [sec_category_id,sec_category_name];
					v.default_msupplier_id = [msupplier_id,msupplier_name];
					
					if(!Array.isArray(v.purchase_unit_id)){
						let purchase_unit_name = material_purchase_unit_category.find(d=>d.id == v.purchase_unit_id).name;
						v.purchase_unit_id = [v.purchase_unit_id,purchase_unit_name];
					}
					
					if(!Array.isArray(v.main_unit_id)){
						let main_unit_name = material_purchase_unit_category.find(d=>d.id == v.main_unit_id).name;
						v.main_unit_id = [v.main_unit_id,main_unit_name];
					}
					
					material_obj[v.id] = v;
					if (!material_tree[top_category_id]) {
						material_tree[top_category_id] = {};
						leftMenus.push({
							id:top_category_id,
							name:top_category_name
						});
					}
					if (!material_tree[top_category_id][msupplier_id]) {
						material_tree[top_category_id][msupplier_id] = {};
						msupplier_obj[msupplier_id] = {
							id: msupplier_id,
							name: msupplier_name
						};
					}
					if (!material_tree[top_category_id][msupplier_id][sec_category_id]) {
						material_tree[top_category_id][msupplier_id][sec_category_id] = {
							id: sec_category_id,
							name: sec_category_name,
							list: []
						}
					}
					material_tree[top_category_id][msupplier_id][sec_category_id].list.push(v);
				});
				// this.menu.forEach(v => {
				// 	if (material_tree[v.id]) {
				// 		leftMenus.push(v);
				// 	}
				// });
				this.msupplier_obj = msupplier_obj;
				this.material_obj = material_obj;
				this.leftMenus = leftMenus;
				this.material_tree = material_tree;
				this.updataMsupplierTabbar(1);
				// this.updataTabbar(1);
			},
			// 份数
			valChange(e) {
				// console.log(e);
				this.valueObj[e.name] = e.value;
				this.$forceUpdate();
				this.updata();

				// 此处待增加 出库数量不能大于库存数量 判断
				// uni.$u.toast('出库数量不能大于库存数量');
			},
			overlimit(e) {
				console.log("overlimit");
				console.log(e);
			},
			add(id) {
				let purchase_start_qty = this.material_obj[id].purchase_start_qty || 1;
				this.valueObj[id] = purchase_start_qty;
				// this.$set(this.valueObj,id,1)
				this.$forceUpdate();
				// this.$set('valueObj',id,1);
				this.updata();
				// console.log(this.valueObj[id]);
			},
			updata() {
				let bagList = [];
				for (let id in this.valueObj) {
					let tips = [];
					if (this.valueObj[id]) {
						let material = this.material_obj[id];
						// console.log(material);
						bagList.push({
							id: parseInt(id),
							name: material.mname,
							value: this.valueObj[id],
							unit_id: material.purchase_unit_id[0],
							unit_name: material.purchase_unit_id[1],
							price: material.main_price,
							msupplier_id: material.default_msupplier_id[0],
							is_quote: material.is_quote,
							mm_id: material.mm_id
						});
					}
				}
				// console.log(bagList);
				this.$emit("updata", bagList);
			},
			updataMsupplierTabbar(isFlesh) {
				let tabbar = [{
					id: 'all',
					name: '全部'
				}];
				let top_category_id = this.leftMenus[this.leftMenusCurrent].id;
				for (let id in this.material_tree[top_category_id]) {
					tabbar.push(this.msupplier_obj[id]);
				}
				this.msupplierTabbar = tabbar;
				if (isFlesh) {
					this.msupplierTabbarCurrent = 0;
					this.updataTabbar(isFlesh);
				}
			},
			updataTabbar(isFlesh) {
				let tabbar = [
					{
						id: 'all',
						name: '全部'
					},
					{
						id: 'sel_weight',
						name: '常用'
					},
					{
						id: 'sel_weight_small',
						name: '不常用'
					}
				];

				let top_category_id = this.leftMenus[this.leftMenusCurrent].id;
				let msupplier_id = this.msupplierTabbar[this.msupplierTabbarCurrent].id;
				if (msupplier_id == 'all') {
					for (let msupplier_id in this.material_tree[top_category_id]) {
						for (let id in this.material_tree[top_category_id][msupplier_id]) {
							let tabbar_item = this.material_tree[top_category_id][msupplier_id][id];
							if (!tabbar.find(v => v.id == tabbar_item.id)) {
								tabbar.push(tabbar_item);
							}
						}
					}
				} else {
					for (let id in this.material_tree[top_category_id][msupplier_id]) {
						tabbar.push(this.material_tree[top_category_id][msupplier_id][id]);
					}
				}
				this.tabbar = tabbar;
				if (isFlesh) {
					this.tabbarCurrent = 0;
					this.list = [];
					setTimeout(() => {
						this.updataList();
					}, 0)
				}
			},
			async updataList(id) {
				this.list = [];
				setTimeout(() => {
					let top_category_id = this.leftMenus[this.leftMenusCurrent].id;
					let msupplier_id = this.msupplierTabbar[this.msupplierTabbarCurrent].id;
					let sec_category_id = this.tabbar[this.tabbarCurrent].id;
					let list = [];
					list = this.data.filter(v => v.top_category_id[0] == top_category_id);
					if (msupplier_id != 'all') {
						list = list.filter(v => v.default_msupplier_id[0] == msupplier_id);
					}
					if (sec_category_id != 'all' && sec_category_id != "sel_weight" && sec_category_id != 'sel_weight_small') {
						list = list.filter(v => v.sec_category_id[0] == sec_category_id);
					}
					if (sec_category_id == 'sel_weight') {
						list = list.filter(v => Number(v.sel_weight) >= 4);
						list.sort((a, b) => Number(b.sel_weight) - Number(a.sel_weight));
					};
					if (sec_category_id == 'sel_weight_small') {
						list = list.filter(v => Number(v.sel_weight) < 4);
						list.sort((a, b) => Number(b.sel_weight) - Number(a.sel_weight));
					};
					list = list.filter(v => {
						if (!v.is_quote && this.is_material) {
							return true;
						}
						if (v.is_quote && this.is_quote) {
							return true;
						}
						return false;
					});
					this.sortList(list);
					this.allList = list;
					if (id) {
						let _index = list.findIndex(v => v.id == id);
						this.list = list.slice(0, _index + 10);
					} else if (list.length > this.pageSize) {
						this.list = list.slice(0, this.pageSize);
					} else {
						this.list = list
					}

					this.$nextTick(() => {
						if (id) {
							this.scrollViewId = 'scrollView_' + id;
						} else if (list.length > 0) {
							this.scrollViewId = 'scrollView_' + list[0].id
						}
						this.$emit('scrollViewIdDone');
					})
				}, 0)

			},
			scrolltolower() {
				let _length = this.list.length;
				let _all_length = this.allList.length;
				if (_length == _all_length) {
					return;
				}
				let newList = this.allList.slice(_length, this.pageSize + _length);
				this.list = this.list.concat(newList);
			},
			tabClick(e) {
				this.tabbarCurrent = e.index;
				this.updataList();
			},
			// 点击左边的栏目切换
			swichMenu(index) {
				if (index == this.current) return;
				this.leftMenusCurrent = index;
				this.updataMsupplierTabbar(1);
			},
			msupplierTabClick(e) {
				this.msupplierTabbarCurrent = e.index;
				this.updataTabbar(1);
				// this.updataList();
			},
			materialEdit(v) {
				let detail = JSON.stringify(v);
				if (v.is_quote) {
					this.nav('/materialEdit/materialEdit?is_quote=1&detail=' + detail+'&from='+this.page);
				} else {
					this.nav('/materialEdit/materialEdit?id=' + v.id + '&detail=' + detail+'&from='+this.page);
				}
			}
		},
	}
</script>

<style lang="scss" scoped>
	@import "./purchase-material-list.scss";

	.btn-picker {
		padding: 4upx 10upx;
		background-color: #ffffff;
		margin-left: 15upx;
		margin-right: 15upx;
		border-radius: 8upx;
		border: 1px solid #675f91;
		font-size: 24upx;
		color: #675f91;
	}

	.info-item {
		// margin-right: 30upx;
		padding: 10upx 30upx 0 0;
	}

	.info-item:last-child {
		padding-right: 0;
	}
</style>